package com.course.finalproject.manager;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;

import com.course.finalproject.Constants;
import com.course.finalproject.MyApplication;
import com.course.finalproject.R;
import com.course.finalproject.model.BatteryLog;
import com.course.finalproject.service.BatteryService;
import com.course.finalproject.ui.BatteryActivity;

public class BatteryManager {

	/** Broadcast receiver for battery changes notified by android system. */
	private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Intent servBatteryIntent = new Intent(MyApplication.getInstance().getApplicationContext(), BatteryService.class); 
			servBatteryIntent.putExtras(intent);
			MyApplication.getInstance().startService(servBatteryIntent);
		}
	};
	
	/** List of battery logs. */
	private List<BatteryLog> batteryLogs;
	/** Local broadcast receiver for actualize the list of battery logs. */
	private BroadcastReceiver batteryLogUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// Extract the battery log from the bundle and put it in the list of logs.
			Bundle bundle = intent.getExtras();
			BatteryLog log = bundle.getParcelable(Constants.BATTERY_LOG_PARCEL_KEY);
			batteryLogs.add(log);
			// Notify in status bar.
			notificationManager.notify(0, getNotification("Battery: " + log.getBatteryPercentage() + "%",
										  				  "New battery update: " + log.getBatteryPercentage() + "%"));
    	}
	};
	
	/** Notification manager. */
	private NotificationManager notificationManager;


	/**
	 * Constructor.
	 */
	public BatteryManager() {
		// Get the NotificationManager to show battery events in status bar.
		notificationManager = (NotificationManager) MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
		// Create the battery log list.
		batteryLogs = new ArrayList<BatteryLog>();
		// Register to receive a new battery log to put it in the list of logs.
		LocalBroadcastManager.getInstance(MyApplication.getInstance()).registerReceiver(batteryLogUpdateReceiver, new IntentFilter(Constants.NEW_LOG_BATTERY_MSG));
		// Register the battery broadcast receiver.
		MyApplication.getInstance().registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}
	
	/**
	 * Destructor.
	 */
	public void destructor() {
		// Unregister the list update of battery logs.
		LocalBroadcastManager.getInstance(MyApplication.getInstance()).unregisterReceiver(batteryLogUpdateReceiver);
		// Unregister the battery broadcast receiver.
		MyApplication.getInstance().unregisterReceiver(batteryReceiver);
	}
	
	/**
	 * Returns the battery log list.
	 * 
	 * @return The battery log list.
	 */
	public List<BatteryLog> getBatteryLogs() {
		return batteryLogs;
	}
	
	/**
	 * Clear the entire battery log list.
	 */
	public void clearBatteryLog() {
		// Clear battery logs list.
		batteryLogs.clear();
		// Cancel all battery notifications.
		notificationManager.cancelAll();
	}
	
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	private Notification getNotification(String text, String ticker) {
		// UI variables.
		String title = "New battery update";
		int icon = R.drawable.ic_launcher;
		// Create the intent notification.
		Intent notificationIntent = new Intent(MyApplication.getInstance(), BatteryActivity.class);
		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent contentIntent = PendingIntent.getActivity(MyApplication.getInstance(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		// Build the battery event status bar notification depending on the android api version.
		Notification batteryNotification;
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
			batteryNotification = new Notification(icon, ticker, System.currentTimeMillis());
			batteryNotification.setLatestEventInfo(MyApplication.getInstance(), title, text, contentIntent);
			batteryNotification.flags = Notification.FLAG_AUTO_CANCEL;
		} else {
			Notification.Builder builder = new Notification.Builder(MyApplication.getInstance())
					.setContentTitle(title)
					.setContentText(text)
					.setTicker(ticker)
					.setSmallIcon(icon)
					.setContentIntent(contentIntent)
					.setAutoCancel(true);
			batteryNotification = builder.build();
		}
		// Return the notification created.
		return batteryNotification;
	}
	
}
